from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from bm.content import config
from operator import itemgetter
from Products.Archetypes.public import *

class LastBulletinView(BrowserView):
    """ This class has inheritance from another class
    defined on plone native code - 'BrowserView'
    The main reason for this inheritance is because 
    I want page with almost the same structure
    but with other methods. 
    """

    def getLastBulletin(self, **kwargs):
        """ 
        """
        pc_tool = getToolByName(self, 'portal_catalog')
        query = {

            'portal_type': 'Bulletin',
            'review_state': 'published',
            'sort_on': 'getBulletinDate',
            'sort_order': 'reverse',
        }
        query.update(kwargs)
        return pc_tool(**query)[0]

    def getArticleTypeByNumber(self, number):
        vocab = config.ARTICLE_TYPES

        return vocab.getValue(number, None)


    def getSummary(self, **kwargs):
        """
        """
        pc_tool = getToolByName(self, 'portal_catalog')
        query = {
                 'path':{
                         'query':'/'.join(self.context.getPhysicalPath()),
                         'depth':1,
                         },
                'sort_on':'sortable_title',
                'review_state':'published',
                'portal_type': ('Article',),
                
                        }
        query.update(kwargs)

        return pc_tool(**query)


    def getArticlesByType(self, id_artigo, number):
        """
        """
        pc_tool = getToolByName(self, 'portal_catalog')
        query = {

                'sort_on':'sortable_title',
                'review_state':'published',
                'portal_type': ('Article',),
                'getArticleType': id_artigo,
                'getBulletinNumber': number,
        }

        query.update()

        result = pc_tool(**query)
        final_result = self.getUniqueArticleType(result)

        return final_result

    def getUniqueArticleType(self, list):
        """
        """
        subjects = []
        articles = []
        for a in list:
            for s in a.Subject:
                if s not in subjects:
                    subjects.append(s)
                    articles.append(a)
        return articles

    def getAllArticlesTypes(self):
        """
        """
        vocab = config.ARTICLE_TYPES
        sorted_vocab = sorted(vocab, key=itemgetter(2))
        vocab_display = DisplayList(sorted_vocab)

        return [(v,vocab_display.getValue(v)) for v in vocab_display]
